package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reggie.pojo.AddressBook;
import com.reggie.dao.AddressBookDao;
import com.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookDao addressBookDao;

    @Override
    public List<AddressBook> selectAll() {
        return addressBookDao.selectList(null);
    }

    @Override
    public int updateDefault(Long id) {
        //只可以有一个是默认地址，因此修改其他所有地址为0唯独这个为1
        List<AddressBook> addressBooks = addressBookDao.selectList(null);
        //修改所有的地址为0
        for (AddressBook addressBook : addressBooks) {
            addressBookDao.updateDefault(addressBook.getId(), 0);
        }
        return addressBookDao.updateDefault(id, 1);
    }

    @Override
    public AddressBook getDefault() {
        return addressBookDao.getDefault();
    }

    @Override
    public AddressBook getAddressById(Long id) {
        return addressBookDao.selectById(id);
    }

    @Override
    public Boolean updateAddress(AddressBook addressBook) {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getId, addressBook.getId());
        int update = addressBookDao.update(addressBook, lqw);
        return update > 0;
    }

    @Override
    public AddressBook selectByUserId(Long userId) {
        return addressBookDao.selectByUserId(userId);
    }

    @Override
    public AddressBook selectById(Long id) {
        return addressBookDao.selectById(id);
    }

    @Override
    public void addAddress(AddressBook addressBook) {
        addressBookDao.insert(addressBook);
    }

    @Override
    public int deleteById(Long id) {
        return addressBookDao.deleteById(id);
    }
}
